<?php
// 微信支付配置
$appid = 'wx476ad85e3f8d4026'; // 替换为你的微信公众号或者小程序的 appid
$mch_id = '1648407769'; // 替换为你的微信支付商户号
$key = 'yzs10131594561594560zxcvbnmasdfr'; // 替换为你的微信支付 API 密钥

// 生成随机字符串
function getNonceStr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

// 生成签名
function getSign($params, $key)
{
    ksort($params);
    $string = '';
    foreach ($params as $k => $v) {
        if ($k != 'sign' && $v != '' && !is_array($v)) {
            $string .= $k . '=' . $v . '&';
        }
    }
    $string = rtrim($string, '&');
    $string = $string . '&key=' . $key;
    return strtoupper(md5($string));
}

// 数组转 XML
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_numeric($val)) {
            $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
        } else {
            $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
    }
    $xml .= "</xml>";
    return $xml;
}

// XML 转数组
function xmlToArray($xml)
{
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

// 获取微信支付通知数据
$xmlData = file_get_contents('php://input');
$notifyData = xmlToArray($xmlData);

// 验证签名
$sign = $notifyData['sign'];
unset($notifyData['sign']);
$calculatedSign = getSign($notifyData, $key);

if ($sign === $calculatedSign && $notifyData['return_code'] === 'SUCCESS' && $notifyData['result_code'] === 'SUCCESS') {
    // 签名验证通过，处理支付成功逻辑
    $outTradeNo = $notifyData['out_trade_no'];
    $transactionId = $notifyData['transaction_id'];
    $totalFee = $notifyData['total_fee'];

    // 这里可以添加更新订单状态、记录日志等操作
    // 例如：更新订单状态为已支付
    // $order = Order::where('out_trade_no', $outTradeNo)->first();
    // if ($order) {
    //     $order->status = 'paid';
    //     $order->transaction_id = $transactionId;
    //     $order->save();
    // }

    // 返回成功响应给微信
    $response = [
        'return_code' => 'SUCCESS',
        'return_msg' => 'OK'
    ];
} else {
    // 签名验证失败或支付失败，记录错误信息
    $errorMsg = $notifyData['err_code_des'] ?? $notifyData['return_msg'];
    // 这里可以添加记录错误日志的操作
    // 例如：Log::error('微信支付通知失败: ' . $errorMsg);

    // 返回失败响应给微信
    $response = [
        'return_code' => 'FAIL',
        'return_msg' => $errorMsg
    ];
}

// 将响应数据转换为 XML 并返回
$responseXml = arrayToXml($response);
header('Content-Type: text/xml');
echo $responseXml;